// cart.js
var api = require('../../api.js');
var app = getApp();
Page({

    /**
     * 页面的初始数据
     */
    data: {
        imgServer :  api.default.img_server,

        total_price: 0,
        exchangeTotal:0,
        //cart_check_all: false,
        cart: [],
        unlogined:false,//是否已经登录
        moneyIcon:api.MONEYICON,
        moneyIconOther:api.MONEYICONOTHER,
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {
        var page = this;
        // page.setData({
        //     //cart_check_all: false,
        //     show_cart_edit: false,
        // });
        var token = wx.getStorageSync("token");
        if(!token){
            page.setData({
                unlogined: true,
            });
        }else{
            page.setData({
                unlogined: false,
            });
            page.getCartList();
        }
        
    },
    toLogin(e){
    //  let backurl = e.currentTarget.dataset.url;
    //  let token = wx.getStorageSync("token");
    //  if(!token){
        wx.navigateTo({
          url: '/pages/allow/allow',
          events: {
            acceptDataFromOpenedPage(data) {
              console.log(data);
              if (data.hasLogin){
                wx.navigateBack();
              }
            }
          },
          success: function (res) {
            res.eventChannel.emit('acceptDataFromOpenerPage')
          }
        })
    //  }
    //   else{
    //     wx.navigateTo({
    //       url: backurl,
    //     })
    //   }
    },
    getCartList: function () {
        var page = this;
        var access_token = wx.getStorageSync("access_token");
        //wx.showNavigationBarLoading();
        page.setData({
            show_no_data_tip: false,
        });
        app.request({
            url: api.cart.list,
            success: function (res) {
                if (res.code == 200 && res.data && res.data.length>0) {
                    let data = res.data;
                    for(const item of data){
                        item.checked = false;
                        item.total_price = 0;
                        item.exchangeTotal = 0;
                        item.isEdit = false;
                        item.cartItemsCheckedLen = 0;
                        for(let item2 of item.cartItems){
                            item2.checked = false;
                        }
                    }
                    //data = Object.assign(data,page.data.cart)
                    page.setData({
                        cart: data,
                        total_price: 0,
                        exchangeTotal:0,
                        //cart_check_all: false,
                        show_cart_edit: false,
                    });
                }else{
                    page.setData({
                        show_no_data_tip: true,
                        cart:[]
                    });
                }
                
                //wx.hideNavigationBarLoading();
                //wx.stopPullDownRefresh();
            }
        });
    },
    changeEdit(e){
        let page = this;
        let topindex = e.currentTarget.dataset.topindex;
        let cart = page.data.cart;
        //cart[topindex].isEdit= true;
        let newCart ={};//这样只更新操作的数据，而不是整个cart全部更新一遍
        newCart['cart[' + (topindex) +'].isEdit'] = true
        page.setData(newCart)
    },
    changeDone(e){
        let page = this;
        let topindex = e.currentTarget.dataset.topindex;
        let cart = page.data.cart;
        cart[topindex].isEdit= false;
        page.setData({
            cart : cart
        })
    },
    cartCheck: function (e) {
        var page = this;
        let topindex= e.currentTarget.dataset.topindex;
        var index = e.currentTarget.dataset.index;
        var cart = page.data.cart;
        if (cart[topindex].cartItems[index].checked) {
            cart[topindex].cartItems[index].checked = false;
            if(cart[topindex].checked){
                cart[topindex].checked = false;
            }
        } else {
            cart[topindex].cartItems[index].checked = true;
            let checkLength = 0;
            for(const item of cart[topindex].cartItems){
                if(item.checked ==true){
                    checkLength+=1
                }
            }
            if(checkLength == cart[topindex].cartItems.length){
                cart[topindex].checked = true
            }
        }
        let len =0;//计算当前仓库被选中的商品个数
        for(const item of cart[topindex].cartItems){
            if(item.checked){
                len+=1
            }
        }
        console.log(len);
        let newCartItem={};
        newCartItem['cart[' + (topindex) +']'] = cart[topindex];
        cart[topindex].cartItemsCheckedLen = len;
        page.setData(newCartItem);
        page.updateTotalPrice(topindex);
    },
    depotCheck(e){
        var page = this;
        var index = e.currentTarget.dataset.index;
        var cart = page.data.cart;
        let len = 0;
        if (cart[index].checked) {
            cart[index].checked = false;
        } else {
            cart[index].checked = true;
            len = cart[index].cartItems.length;
        }
        let cartItems = cart[index].cartItems;
        for(const item of cartItems){
            item.checked = cart[index].checked;
        }
        
        cart[index].cartItemsCheckedLen = len;//当前仓库下的所有商品
        let newCart ={};
        newCart['cart['+ (index) +']'] = cart[index]
        page.setData(newCart);
        page.updateTotalPrice(index);
    },
    // cartCheckAll: function () {
    //     var page = this;
    //     var cart_list = page.data.cart_list;
    //     var checked = false;
    //     if (page.data.cart_check_all) {
    //         checked = false;
    //     } else {
    //         checked = true;
    //     }
    //     for (var i in cart_list) {
    //         if (!cart_list[i].disabled || page.data.show_cart_edit)
    //             cart_list[i].checked = checked;
    //     }
    //     page.setData({
    //         cart_check_all: checked,
    //         cart_list: cart_list,
    //     });
    //     page.updateTotalPrice();
    // },
    updateTotalPrice: function (index) {//index是外层的index,根据仓库走
        var page = this;
        //var total_price = 0.00;
        var cart = page.data.cart;
        let idx = index;
        let checkedArr =[];
        for(let item of cart[idx].cartItems){
            if (item.checked){
                checkedArr.push(item.id)
                //total_price += parseInt(item.price)* parseInt(item.quantity);
            }
        }
        if(checkedArr.length ==0) {
            let newCartItem ={};
            newCartItem['cart['+ (idx) + '].total_price']=  0;
            newCartItem['cart['+ (idx) + '].exchangeTotal']=  0;
            page.setData(newCartItem);
            return;
        };
        app.request({
            url:api.cart.getTotalPrice,
            method:"POST",
            data:{
                cartIds:checkedArr
            },
            success(res){
                if(res.code ==200){
                    let total = res.data.totalMoney;
                    let exchangeTotal = res.data.exchangeTotalMoney;
                    let newCartItem ={};
                    newCartItem['cart['+ (idx) + '].total_price']=  total;
                    newCartItem['cart['+ (idx) + '].exchangeTotal']=  exchangeTotal;
                    page.setData(newCartItem);
                }
            }
        })
        
    },
    onNumChange(e){
        let page = this;
        let detail = e.detail;
        let topindex = e.currentTarget.dataset.topindex;
        let index = e.currentTarget.dataset.index;
        let id = e.currentTarget.dataset.id;
        let cart = page.data.cart;
        let newCartItem ={};
        app.request({
            url: api.cart.queryNum,
            data:{
                id:id,
                quantity:detail
            },
            success:function(res){
                if(res.code ==200 && res.data!= -1){
                    newCartItem['cart['+ (topindex) +'].cartItems[' +(index) +'].quantity'] = detail;
                    newCartItem['cart['+ (topindex) +'].cartItems[' +(index) +'].price'] = res.data.price;
                    newCartItem['cart['+ (topindex) +'].cartItems[' +(index) +'].exchangePrice'] = res.data.exchangePrice;
                }else if(res.code !==200){
                    wx.showToast({
                      title: res.message,
                      icon: 'none',
                      duration:2000
                    });
                    newCartItem['cart['+ (topindex) +'].cartItems[' +(index) +'].quantity'] = detail -1;
                    console.log(detail);
                }
               
                page.setData(newCartItem);
                console.log( newCartItem['cart['+ (topindex) +'].cartItems[' +(index) +'].quantity'])
                if(cart[topindex].cartItems[index].checked && res.code ==200){
                    page.updateTotalPrice(topindex);
                }
            }
        })
    },
    cartSubmit: function (e) {
        var page = this;
        var cart = page.data.cart;
        let topindex = e.currentTarget.dataset.topindex; 
        let depotId = e.currentTarget.dataset.depotid;
        let depotName = e.currentTarget.dataset.depotname;
        var cart_id_list = [];
        if(cart[topindex].cartItemsCheckedLen<1){
            wx.showToast({
              title: '请选择需要结算的商品',
              icon: "none",
              duration:2000
            })
            return false;
        }
        for (const item of cart[topindex].cartItems) {
            if (item.checked)
                cart_id_list.push(item.id);
        }
        if (cart_id_list.length == 0) {
            wx.showToast({
                title: '请选择需要结算的商品',
                icon: "none",
                duration:2000
              })
              return false;
        }
        wx.navigateTo({
            url: '/pages/order-submit/order-submit?cart_id_list=' + cart_id_list.join(',')
            +'&depotId='+depotId+'&depotName='+depotName,
        });
    },
    toDetailpage(e){
        let id = e.currentTarget.dataset.id;
        wx.navigateTo({
          url: "/pages/goods/goods?id="+id,
        })
    },
    cartEdit: function () {
        var page = this;
        var cart = page.data.cart;
        for (var i in cart) {
            cart[i].checked = false;
            for(const item of cart[i].cartItems){
                item.checked = false
            }
        }
        page.setData({
            cart: cart,
            show_cart_edit: true,
            //cart_check_all: false,
            total_price:0,
            exchangeTotal:0,
        });
       // page.updateTotalPrice();
    },

    cartDone: function () {
        var page = this;
        var cart_list = page.data.cart_list;
        for (var i in cart_list) {
            cart_list[i].checked = false;
        }
        page.setData({
            cart_list: cart_list,
            show_cart_edit: false,
            //cart_check_all: false,
        });
        page.updateTotalPrice();
    },

    cartDelete: function (e) {
        var page = this;
        let id= e.currentTarget.dataset.id;
        let deleteIds=[];
        deleteIds.push(id);
        wx.showModal({
            title: "提示",
            content: "确认删除该商品吗？",
            success: function (res) {
                if (res.cancel)
                    return true;
                wx.showLoading({
                    title: "正在删除",
                    mask: true,
                });

                app.request({
                    url: api.cart.delete+id,
                    success: function (res) {
                        wx.hideLoading();
                        if (res.code == 200) {
                            //page.cartDone();
                            wx.showToast({
                                title: '删除成功',
                            });
                            page.getCartList();
                        }else{
                            wx.showToast({
                                icon:"none",
                              title: res.message,
                              duration:2000
                            })
                        }
                        
                    }
                });
            }
        });
    },

});